package top.ajunnihao.core.web.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import top.ajunnihao.core.entity.Order;
import top.ajunnihao.core.entity.User;
import top.ajunnihao.core.service.OrderService;
import top.ajunnihao.core.service.UserService;
import top.ajunnihao.core.util.resp.JResp;

import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * <p>
 * 用户前端控制器
 * </p>
 */
@Controller
public class UserController {

    private final static String CAPTCHA_CODE = "CAPTCHA_CODE";
    private final static String USER = "USER";
    private static final Integer ADMIN_SIZE = 7;

    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;

    @GetMapping("/admin/users")
    public String adminListUser(Integer page, Model model) {
        if (page == null) {
            page = 1;
        }
        IPage<User> userPage = userService.page(new Page<>(page, ADMIN_SIZE),
                Wrappers.<User>lambdaQuery()
                        .orderByDesc(User::getUserId)
        );
        model.addAttribute("userPage", userPage);
        return "admin/user-list";
    }

    @GetMapping("/admin/user/search")
    public String adminSearchUserList(Integer page, String name, Model model) {
        if (page == null) {
            page = 1;
        }
        IPage<User> userPage = userService.page(new Page<>(page, ADMIN_SIZE),
                Wrappers.<User>lambdaQuery()
                        .like(User::getUserRealName, name)
                        .orderByDesc(User::getUserId)
        );
        if (CollUtil.isEmpty(userPage.getRecords())) {
            model.addAttribute("searchMsg", "无此记录");
        }
        model.addAttribute("userPage", userPage);
        return "admin/user-list";
    }

    @PostMapping("/admin/user/deleteUser.do")
    @ResponseBody
    public Object adminDeleteUser(@RequestBody JSONObject jReq) {
        long userId = jReq.getLongValue("userId");
        // 删除用户及其关联的所有订单
        boolean flag = userService.removeById(userId);
        List<Order> orderList = orderService.list(
                Wrappers.<Order>lambdaQuery()
                        .select(Order::getOrderId)
                        .eq(Order::getUserId, userId)
        );
        orderList.forEach(order -> orderService.removeById(order.getOrderId()));
        if (!flag) {
            return JResp.error("删除失败，用户 ID = " + userId);
        }
        return JResp.ok("删除成功，用户 ID = " + userId);
    }

    @PostMapping("/admin/user/findUserById.do")
    @ResponseBody
    public Object adminFindUserById(@RequestBody JSONObject jReq) {
        long userId = jReq.getLongValue("userId");
        User user = userService.getById(userId);
        if (user == null) {
            return JResp.error("查询失败");
        }
        return JResp.ok(user, "查询成功");
    }

    @PostMapping("/admin/user/updateUser.do")
    @ResponseBody
    public Object adminUpdateUserById(@RequestBody User user) {
        boolean flag = userService.updateById(user);
        if (!flag) {
            return JResp.error("更新失败，用户 ID = " + user.getUserId());
        }
        return JResp.ok(user, "更新成功，用户 ID = " + user.getUserId());
    }

    @PostMapping("/user/register.do")
    @ResponseBody
    public Object userRegister(@RequestBody JSONObject jReq, HttpSession session) {
        User user = jReq.getObject("user", User.class);
        String captchaCode = jReq.getString("captchaCode");

        // 验证码验证
        String captcha = (String) session.getAttribute(CAPTCHA_CODE);
        session.removeAttribute(CAPTCHA_CODE); // 用完立刻清除 session 中的验证码
        if (captcha == null || !captcha.equalsIgnoreCase(captchaCode)) {
            return JResp.error("验证码错误");
        }

        // 计算年龄
        LocalDate today = LocalDate.now();
        int age = (int) ChronoUnit.YEARS.between(user.getUserBirth(), today);
        user.setUserAge(age);

        // 注册
        User u = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUserRealName, user.getUserRealName()));
        if (u != null) {
            return JResp.error("用户已被注册");
        }
        // 保存用户
        boolean flag = userService.save(user);
        if (flag) {
            return JResp.ok(user, "注册成功");
        } else {
            return JResp.error("注册失败");
        }
    }

    @PostMapping("/user/login.do")
    @ResponseBody
    public Object userLogin(@RequestBody User user, HttpSession session) {
        // 查询用户
        User u = userService.getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUserNickname, user.getUserNickname())
                .eq(User::getUserPassword, user.getUserPassword())
        );
        if (u == null) {
            return JResp.error("用户名或密码错误");
        }

        // 存入 Session
        session.setAttribute(USER, u);
        return JResp.ok("登录成功");
    }

    @PostMapping("/user/logout.do")
    @ResponseBody
    public Object userLogout(HttpSession session) {
        session.removeAttribute(USER);
        return JResp.ok("退出登录成功");
    }

}
